package com.gzwanchuang.xhgj.ui.page.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.gzwanchuang.xhgj.BuildConfig;
import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.app.App;
import com.gzwanchuang.xhgj.bridge.data.bean.ServiceBean;
import com.gzwanchuang.xhgj.bridge.data.bean.UserBean;
import com.gzwanchuang.xhgj.bridge.data.repository.Apis;
import com.gzwanchuang.xhgj.bridge.request.MineRequestViewModel;
import com.gzwanchuang.xhgj.bridge.state.main.MineFragmentViewModel;
import com.gzwanchuang.xhgj.databinding.FragmentMineBinding;
import com.gzwanchuang.xhgj.help.UserHelper;
import com.gzwanchuang.xhgj.bridge.data.repository.WebApis;
import com.gzwanchuang.xhgj.net.NetworkManager;
import com.gzwanchuang.xhgj.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.xhgj.proto.Mergedintoaccount;
import com.gzwanchuang.xhgj.ui.base.BaseFragment;
import com.gzwanchuang.xhgj.ui.web.ui.WebViewActivity;
import com.google.protobuf.InvalidProtocolBufferException;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class MineFragment extends BaseFragment {


    private FragmentMineBinding mBinding;
    private MineFragmentViewModel mViewModel;
    private MineRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MineFragmentViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(MineRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        mBinding = FragmentMineBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRequestViewModel.getErrorString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });
        mRequestViewModel.getResultString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });
        mRequestViewModel.getMember().observe(this, member -> {
            UserBean userBean = new UserBean(member);
            UserHelper.syncCurrentUserInfo(userBean);
            mViewModel.info.set(userBean);
        });
        mRequestViewModel.getKfuBean().observe(this, get_kfu_info -> {

            ServiceBean serviceBean = new ServiceBean();
            serviceBean.setMember_id(get_kfu_info.getMemberId());
            serviceBean.setMember_name(get_kfu_info.getMemberName());
            serviceBean.setMember_mobile(get_kfu_info.getMemberMobile());
            serviceBean.setMember_avatar(get_kfu_info.getMemberAvatar());
            serviceBean.setChat_id(get_kfu_info.getChatId());
            serviceBean.setChat_pwd(get_kfu_info.getChatPwd());
            UserHelper.saveKeFuUserInfo(serviceBean);
        });
        mRequestViewModel.getMemberInfo();
        mRequestViewModel.get_kfu_info();


        NetworkManager.INSTANCE.post(Apis.pattern_query, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Mergedintoaccount.pattern_query pattern_query = Mergedintoaccount.pattern_query.parseFrom(response);
                Log.e("tag", pattern_query.toString());

                if (pattern_query.getType().equals("SELF")) {
                    mViewModel.moType.set("1");
                } else {
                    mViewModel.moType.set("2");
                }

            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });


    }


    private void startChat() {
        boolean login = ChatHelper.getInstance().isLogin();
        if (login) {
            // 打开客服聊天
            ServiceBean keFuInfo = UserHelper.getKeFuInfo();
            ChatActivity.startActivity(mActivity, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
        } else {
            showShortToast("聊天登录中");
            App.getChatHelper().login(UserHelper.getUser().getChat_id(), UserHelper.getUser().getChat_pwd(), new LoginCallBack() {
                @Override
                public void onSuccess() {
                    //判断是否为客服
                    // 打开客服聊天
                    ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                    mActivity.runOnUiThread(() -> showShortToast("人工客服回复时间：工作日9:00-12:00；13:30-18:00"));
                    ChatActivity.startActivity(mActivity, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
                }

                @Override
                public void onError(int code, String message) {
                    mActivity.runOnUiThread(() -> showShortToast("聊天暂时登录失败"));
                }
            });
        }
    }

    public class ClickProxy {
        public void GoToNext(View view) {
            switch (view.getId()) {
                case R.id.rv_jiesuanka:
                    nav().navigate(R.id.action_mainRootFragment_to_jieSuanKaFragment);
                    break;
                case R.id.rv_hexiaozhang:
                    showProgress();
                    NetworkManager.INSTANCE.post(Apis.pattern_query, new OnRequestCallBack() {
                        @Override
                        public void onOk(byte[] response) throws InvalidProtocolBufferException {
                            hideProgress();
                            Mergedintoaccount.pattern_query pattern_query = Mergedintoaccount.pattern_query.parseFrom(response);
                            Log.e("tag", pattern_query.toString());

                            if (pattern_query.getType().equals("SELF")) {
                                mViewModel.moType.set("1");
                            } else {
                                mViewModel.moType.set("2");
                            }

                            if (mViewModel.moType.get().equals("1")) {
                                // 跳转另外一个页面
                                Bundle bundle = new Bundle();
                                bundle.putString("type", "1");
                                nav().navigate(R.id.action_mainRootFragment_to_heXiaoZhangChaFragment, bundle);
                            } else {
                                Bundle bundle = new Bundle();
                                bundle.putString("type", "2");
                                nav().navigate(R.id.action_mainRootFragment_to_heXiaoZhangChaFragment, bundle);

                            }
                        }

                        @Override
                        public void onError(int errorCode, String errorMessage) {
                        }
                    });
                    break;
                case R.id.rv_setting:
                    nav().navigate(R.id.action_mainRootFragment_to_mineSettingFragment);
                    break;
                case R.id.rv_kefu:
                    startChat();
                    break;
                case R.id.rv_wenti:
                    WebViewActivity.startActivity(mActivity, BuildConfig.SERVERHEAD + WebApis.commonProblem);
                    break;
                case R.id.rv_feedback:
                    nav().navigate(R.id.action_mainRootFragment_to_feedBackFragment);
                    break;
                case R.id.rv_info:
                    nav().navigate(R.id.action_mainRootFragment_to_mineInfoFragment);
                    break;
                case R.id.rv_sebei:
                    nav().navigate(R.id.action_mainRootFragment_to_sheBeiFragment);
                    break;

                case R.id.rv_da_biao:
                    WebViewActivity.startActivity(mActivity, BuildConfig.SERVERHEAD + WebApis.reward);
                    break;
            }
        }
        public void setting() {
            nav().navigate(R.id.action_mainRootFragment_to_mineSettingFragment);
        }

        /**
         * 拨打电话（跳转到拨号界面，用户手动点击拨打）
         */
        public void takePhone() {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + mViewModel.phone.get());
            intent.setData(data);
            startActivity(intent);
        }
    }
}
